package com.springcloud.sc.ucpv5.client.module.map.util;


import java.io.File;
import java.io.FileInputStream;
import com.springcloud.sc.ucpv5.client.module.map.data.MapTileLoadData;

public class MapTileUtil {

    public static byte[] getTile(MapTileLoadData tileData) {
        try{
            StringBuilder builder = new StringBuilder();

            String tileUrl = tileData.url;
            String map_dir = tileData.mapType;
            String tileBaseKey = tileData.baseKey;

            builder.append("瓦片请求:");
            builder.append(map_dir);
            builder.append(":");
            builder.append(tileBaseKey);
            builder.append(":");
            builder.append(tileUrl);

            // 配置文件是否制定路径
            String systmeMapDir = "d:\\mapdata";

            String[] tmps = tileBaseKey.split("_");
            if(tmps.length == 3){
                String x = tmps[0];
                String y = tmps[1];
                String zoom = tmps[2];

                try {
                    String[] tmps_ = tmps[2].split("\\.");
                    if(tmps_.length == 2){
                        zoom = tmps_[0];
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if(map_dir.equals("mapAbc")){
                    map_dir = "mapabc/roadmap";
                    StringBuffer buffer = new StringBuffer();
                    buffer.append("\\");
                    buffer.append(zoom);
                    buffer.append("\\");
                    buffer.append(x);
                    buffer.append("\\");
                    buffer.append(y);
                    buffer.append(".");
                    buffer.append("png");
                    tileBaseKey= buffer.toString();
                }
            }

            String fileName = systmeMapDir + File.separator + "tile_res" + File.separator + map_dir + File.separator + tileBaseKey;
            if (systmeMapDir != null && !systmeMapDir.equals("")) {
                fileName = systmeMapDir + File.separator + "tile_res" + File.separator + map_dir + File.separator + tileBaseKey;
            }

            builder.append(" 文件路径:" + fileName);

            File cacheFile = new File(fileName);
            byte data[] = null;

            if (cacheFile.isFile() && cacheFile.exists()) {
                builder.append(" 本地缓存获取成功");
                FileInputStream fis = new FileInputStream(cacheFile);
                int size = fis.available();
                data = new byte[size];
                fis.read(data);
                fis.close();
            }
            // 打印结果
            System.out.println(builder.toString());

            return data;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;

    }
}
